﻿using System;
using System.Timers;
using PengSW.NotifyPropertyChanged;
using PengSW.RuntimeLog;

namespace PengSW.Monitor
{
    public class Monitor : NotifyPropertyChangedObject
    {
        public Monitor(string aName, IMonitorTarget aMonitorTarget, double aInterval)
        {
            Name = aName;
            m_MonitorTarget = aMonitorTarget;
            m_MonitorTimer = new Timer();
            m_MonitorTimer.Interval = aInterval;
            m_MonitorTimer.Elapsed += m_MonitorTimer_Elapsed;
        }

        public void Start()
        {
            m_MonitorTimer.Start();
            OnPropertyChanged(nameof(IsMonitoring));
        }

        public void Stop()
        {
            m_MonitorTimer.Stop();
            OnPropertyChanged(nameof(IsMonitoring));
        }

        public bool IsMonitoring { get { return m_MonitorTimer.Enabled; } }

        private void m_MonitorTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                IsAlive = m_MonitorTarget.IsAlive;
            }
            catch (Exception ex)
            {
                IsAlive = false;
                RL.E(ex, false, true, string.Format("[{0}] Monitor Test", m_MonitorTarget.Description));
            }
        }

        private IMonitorTarget m_MonitorTarget;
        private Timer m_MonitorTimer;

        private bool m_IsAlive;
        public bool IsAlive { get { return m_IsAlive; } private set { SetValue(ref m_IsAlive, value, nameof(IsAlive)); } }

        public string Description { get { return m_MonitorTarget.Description; } }

        public string Name { get; private set; }
    }
}
